/**
 * Created by zhangyw on 2018/2/2.
 */
Vue.config.devtools = true;
Vue.config.errorHandler = function (err, vm) {
    console.log(err, vm)
};

// 自定义菜单组件
Vue.component('v-menu', {
    template: "<li :class=\"[{'active':open}]\">\n" +
    "		<a @click=\"toggle\">" +
    "				<i :class=\"model.icon\"></i>" +
    "				<span class=\"text\">{{model.title}}</span>" +
    "				<i v-if=\"isFolder\" class=\"toggle-icon\"" +
    "					 :class=\"[{'fa fa-angle-down':open}, {'fa fa-angle-right':!open}]\"></i>" +
    "		</a>" +
    "		<ul v-if=\"isFolder\" class=\"sub-menu\" :class=\"{open:open}\">" +
    "				<v-menu v-for=\"menu in model.subs\" :model=\"menu\"></v-menu>" +
    "		</ul>" +
    "</li>",
    props: {model: Object},
    data: function () {
        return {
            url: '#'
        }
    },
    computed: {
        isFolder: function () {
            return this.model.subs && this.model.subs.length > 0;
        },
        open: function () {
            var menu_choose = sessionStorage.getItem("menu_choose");

            if (this.model.id == menu_choose) {
                return true;
            }

            var href = window.location.href;
            var checkOpen = function (href, menu) { // 子节点有一个展开 则展开
                if (href.indexOf(menu.url) > 0 || menu.id == menu_choose) {
                    return true;
                }

                for (var i = 0; i < menu.subs.length; i++) {
                    var child = menu.subs[i];
                    if (checkOpen(href, child)) {
                        return true;
                    }
                }
                return false;
            };

            return checkOpen(href, this.model);
        }
    },
    methods: {
        toggle: function () {
            if (this.isFolder) {
                this.open = !this.open;

                // 控制菜单效果
                var $li = $(this.$el);
                if (!$li.hasClass('active')) {
                    $li.find(' > a .toggle-icon').removeClass('fa-angle-right').addClass('fa-angle-down');
                    $li.addClass('active');
                    $li.find(' > ul.sub-menu').slideDown(300, function () {
                        $li.addClass('open')
                    });
                } else {
                    $li.find(' > a .toggle-icon').removeClass('fa-angle-down').addClass('fa-angle-right');
                    $li.removeClass('active');
                    $li.find(' > ul.sub-menu').slideUp(300, function () {
                        $li.removeClass('open')
                    });
                }

            } else {
                // var menu_choose = sessionStorage.getItem("menu_choose");

                // if (this.model.id != menu_choose){
                sessionStorage.setItem("menu_choose", this.model.id);
                http.route(this.model.url, null, this.model.target);
                // }
            }
            return false;
        }
    }
});

$(document).ready(function () {
    // 菜单控件
    var menu = new Vue({
        el: '#left-menu',
        data: {menus: []},
        components: ['v-menu'],
        methods: {
            loadMenu: function () {
                var _self = this;
                //[
                // {"hasChilds":true,"icon":"border_color","id":79,"subs":[{"hasChilds":false,"icon":"border_color","id":80,"subs":[],"target":"_self","title":"搜索数据","url":"123"}],"target":"_self","title":"数据透视","url":""},
                // {"hasChilds":true,"icon":"border_color","id":81,"subs":[{"hasChilds":false,"icon":"border_color","id":82,"subs":[],"target":"_self","title":"推送控制台","url":"123"}],"target":"_self","title":"推送中心","url":""}]
                var _menu = sessionStorage.getItem('menu');
                if (!_menu) {
                    userAuthc.loadMenu().then(function (res) {
                        if (res.code == 1) {
                            _menu = JSON.stringify(res.data);
                            sessionStorage.setItem('menu', _menu);
                            _self.menus = res.data;
                        }
                    });
                } else {
                    _self.menus = JSON.parse(_menu);
                }
            },
            reloadMenu: function () {
                var _menu = sessionStorage.getItem('menu');
                this.menus = JSON.parse(_menu);
            }
        },
        mounted: function () {
            this.loadMenu();
        }
    });

    // 个人中心控件
    var userinfo = new Vue({
        el: '#userinfo',
        data: {},
        methods: {
            changePwd: function () {
                // http.route('manager/passwdReset.html');
            },
            logout: function () {
                userAuthc.doLogout().then(function () {
                    sessionStorage.clear();
                    http.route('login.html')
                });
            }
        }
    });

    // 消息通知
    var notifyinfo = new Vue({
        el: '#notifyInfo',
        data: {
            num: 0,
            notifies: []
        },
        methods: {
            readMsg: function (msg) {
                msg.status = 1;
                http.post("/admin/notice/save", msg).then(function (res) {
                    if (res.code == 1) {
                        sessionStorage.removeItem("notifiesnum");
                        sessionStorage.removeItem("notifiesdata");
                        http.route(msg.link);
                    }
                })
            },
            loadNotify:function () {
                http.get("/admin/notice").then(function (res) {
                    if (res.code == 1) {
                        notifyinfo.num = res.data.total;
                        sessionStorage.setItem('notifiesnum', res.data.total);
                        notifyinfo.notifies = res.data.rows;
                        sessionStorage.setItem('notifiesdata', JSON.stringify(res.data.rows));
                    }
                });
            }
        },
        mounted:function () {
            this.loadNotify();
            // 每隔一分钟查询一次通知消息
            setInterval(this.loadNotify, 60000);
        }
    });

    /************************
     /*    LAYOUT
     /************************/
    var bodySidebarFixed = $('body.sidebar-fixed');
    var leftSidebar = $('#left-sidebar');
    var contentWrapper = $('#content-wrapper');
    // set minimum height for content wrapper
    $(window).bind("load resize scroll", function () {
        calculateLeftSidebarScroll();
        calculateContentHeight();
    });

    function calculateLeftSidebarScroll() {
        // slimscroll left navigation
        if (bodySidebarFixed.length > 0) {
            bodySidebarFixed.find('.sidebar-scroll').slimScroll({
                height: 'auto',
                wheelStep: 5,
                size: '0'
            });
        }
    }

    function calculateContentHeight() {
        contentWrapper.css('height', $(window).height() - 55);
    }
    calculateLeftSidebarScroll();
    calculateContentHeight();

    /************************
     /*    MAIN NAVIGATION
     /************************/
    // checking for minified left sidebar
    $('.toggle-sidebar-collapse').on('click', function () {
        // if ($(window).width() > 992) {
        // use float sidebar
        if (!leftSidebar.hasClass('sidebar-float-active')) {
            leftSidebar.addClass('sidebar-float-active').addClass("minified");
            contentWrapper.addClass('expanded');
            localStorage.setItem("menu-minified", '1');
        } else {
            leftSidebar.removeClass('sidebar-float-active').removeClass("minified");
            contentWrapper.removeClass('expanded');
            localStorage.setItem("menu-minified", '0');
        }
        // } else {
        //     // use collapsed sidebar
        //     if (!leftSidebar.hasClass('sidebar-hide-left')) {
        //         leftSidebar.addClass('sidebar-hide-left');
        //         contentWrapper.addClass('expanded-full');
        //     } else {
        //         leftSidebar.removeClass('sidebar-hide-left');
        //         contentWrapper.removeClass('expanded-full');
        //     }
        // }
    });

    function checkMenuMinified() {
        var menuMinified = localStorage.getItem("menu-minified");
        menuMinified = menuMinified || '0';
        if (menuMinified == '1' && !leftSidebar.hasClass('sidebar-float-active')) {
            leftSidebar.addClass('sidebar-float-active').addClass("minified");
            contentWrapper.addClass('expanded');
        }
    }

    checkMenuMinified();

    // 跳转主页
    $('#goHome').bind('click', function () {
        sessionStorage.removeItem("menu_choose");
        http.route('index.html', null, '_self');
    })
});